package com.onec.service.gateway.config;

import com.onec.service.api.enums.ResultCodeEnum;
import com.onec.service.api.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: ${todo}(来自网络gateway api 统一异常处理)
 * @Author: zzh
 * @Modified By:
 * @Date: 2019/2/21 15:16
 */
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(JsonExceptionHandler.class);

    public JsonExceptionHandler(ErrorAttributes errorAttributes, WebProperties webProperties,
                                ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, webProperties.getResources(), errorProperties, applicationContext);
    }

    /**
     * 获取异常属性
     */

    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        int code = ResultCodeEnum.SERVER_ERROR.getCode();
        String message = ResultCodeEnum.SERVER_ERROR.getMessage();
        Throwable error = super.getError(request);
        if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
            code = ResultCodeEnum.NOT_FOUND.getCode();
            message = ResultCodeEnum.NOT_FOUND.getMessage();
        }
//        if(error instanceof  ){}
        if (error instanceof BaseException) {
            code = ((BaseException) error).code;
            message = ((BaseException) error).message;
        }
        log.info("服务请求异常：URI:{},CODE:{},MESSAGE:{}", request.uri(), code, message);

        return response(code, this.buildMessage(request, message));
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     *
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    /**
     * 根据code获取对应的HttpStatus
     *
     * @param errorAttributes
     */
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        return (int) errorAttributes.get("code");
    }

    /**
     * 构建异常信息
     *
     * @param request
     * @param msg
     * @return
     */
    private String buildMessage(ServerRequest request, String msg) {
        StringBuilder message = new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.uri());
        message.append("]");
        if (msg != null) {
            message.append(": ");
            message.append(msg);
        }
        return message.toString();
    }

    /**
     * 构建返回的JSON数据格式
     *
     * @param status       状态码
     * @param errorMessage 异常信息
     * @return
     */
    public static Map<String, Object> response(int status, String errorMessage) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", status);
        map.put("message", errorMessage);
        map.put("data", "");
        return map;
    }

}
